package com.datoucai.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datoucai.param.BaseResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(basePackages="com.datoucai.controller")
public class GlobalExceptionHandler {

    private static final Log log = LogFactory.get();


//    统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody//返回json串
    public BaseResult error(HttpServletRequest request, Exception e) throws Throwable {
         if (e instanceof BlockException) {
            throw e; // 继续抛出，由Sentinel处理
        }
        Tracer.trace(e);
        log.error("异常信息：",e);
        return BaseResult.error();
    }

    // 捕获所有 BlockException
//    @ExceptionHandler(BlockException.class)
//    @ResponseBody
//    public ResponseEntity<String> handleBlockException(BlockException ex) {
//        if (ex instanceof FlowException) {
//            return ResponseEntity.status(503).body("服务限流");
//        } else if (ex instanceof ParamFlowException) {
//            return ResponseEntity.status(503).body("热点参数限流");
//        } else if (ex instanceof DegradeException) {
//            return ResponseEntity.status(503).body("服务熔断");
//        } else if (ex instanceof SystemBlockException) {
//            return ResponseEntity.status(503).body("系统规则触发");
//        } else if (ex instanceof AuthorityException) {
//            return ResponseEntity.status(503).body("权限规则触发");
//        }
//        return ResponseEntity.status(503).body("服务不可用");
//    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody//返回json串
    public BaseResult customError(HttpServletRequest request, CustomException e){
        Tracer.trace(e);
        return BaseResult.error(e.getCode(), e.getMsg());
    }
}